package com.controller;

import com.model.Book;
import com.model.BrowRecored;
import com.model.User;
import com.service.BookService;
import com.service.BrowRecoredService;
import com.service.UserService;
import com.util.EmailSendUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RequestMapping("book")
@Controller
public class BookController {

    @Autowired
    BookService bookService;

    @Autowired
    private BrowRecoredService browRecoredService;
    @Autowired
    private UserService userService;
    @Autowired
    private EmailSendUtil emailSend;
    //展示书籍的信息
    @RequestMapping("showBook.do")
    @ResponseBody
    public HashMap<String,Object> showBook(Book book, String limit, String page){

        HashMap<String, Object> mapBook = bookService.selectPage(book,limit,page);
        HashMap<String ,Object> map = new HashMap<>();
        System.out.println(mapBook.get("total"));
        System.out.println(mapBook.get("list"));
        map.put("code",0);
        map.put("msg","");
        map.put("count",mapBook.get("total"));
        map.put("data",mapBook.get("list"));
        return map;
    }
    @RequestMapping("showBookByTiaojian.do")
    @ResponseBody
    public HashMap<String,Object> ByTiaojian(String bookName,String varies, String limit, String page){

        HashMap<String, Object> mapBook = bookService.selectPage2(bookName,varies,limit,page);
        HashMap<String ,Object> map = new HashMap<>();
        System.out.println(mapBook.get("total"));
        System.out.println(mapBook.get("list"));
        map.put("code",0);
        map.put("msg","");
        map.put("count",mapBook.get("total"));
        map.put("data",mapBook.get("list"));
        return map;
    }




    //待还图书--普通用户
    //跳转待还图书页面
    @RequestMapping("nowBrowListUI.do")
    public String nowBrowListUI(){
        return "nowBrowList";
    }
    //ajax请求返回数据
    @RequestMapping(value = "nowBrowList.do",produces = "application/json;charset=utf-8")
    @ResponseBody
    public List<BrowRecored> nowBrowList(HttpSession httpSession){
        User user = (User) httpSession.getAttribute("user");
        Integer userId = user.getUserid();
        List<BrowRecored> nowBrowList = bookService.queryNowBrowListByUserId(userId);
        System.out.println("-----"+nowBrowList.toString());
        return nowBrowList;
    }
    //用户归还图书操作
    @RequestMapping(value = "judgeIsOutTime.do",produces = "application/json;charset=utf-8")
    @ResponseBody
    public int judgeIsOutTime(BrowRecored browRecored) throws ParseException {
        System.out.println("--------judgeIsOutTime--------------");
        //1.得到要归还的browRecored_db对象
        BrowRecored browRecored_db = browRecoredService.queryBrowRecoredById(browRecored.getBrowRecoredId());
        //2.计算归还时间是否逾期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d=sdf.parse(browRecored_db.getBrowDate());
        long returnTime = new Date().getTime();
        long broweTime = d.getTime();
        long compareTime = 2592000000L;
        if ((returnTime-broweTime)>compareTime){
            //3.得到用户对象--进行逾期处罚
            User user_db = userService.queryUserByUserId(browRecored_db.getUserId());
            //可借书籍-1，信用分-10
            Integer newDefaultNumber = user_db.getDefaultNumber()-1;
            Integer newCreditScore = user_db.getCreditScore()-10;
            user_db.setDefaultNumber(newDefaultNumber);
            user_db.setCreditScore(newCreditScore);
            //4.修改用户数据
            int i = userService.updateByPrimaryKeySelective(user_db);
        }
        //5.修改记录表的状态bookState（0借书等待，1借出，2还书等待，3归还成功）
        browRecored_db.setBookState(2);
        int m = browRecoredService.updateByPrimaryKeySelective(browRecored_db);
        System.out.println(m);
        return 0;
    }

    //处理图书--管理员
    @RequestMapping("handleBookListUI.do")
    public String handleBook(){
        return "handleBookList";
    }
    //用户处理图书页面显示
    @RequestMapping(value = "handleList.do",produces = "application/json;charset=utf-8")
    @ResponseBody
    public List<BrowRecored> handleBookList(HttpSession httpSession){
        User user = (User) httpSession.getAttribute("user");
        Integer userId = user.getUserid();
        List<BrowRecored> handleBookList = bookService.queryHandleListByUserId(userId);
        return handleBookList;
    }
    //用户处理图书操作
    @RequestMapping(value = "restoreShelves.do",produces = "application/json;charset=utf-8")
    @ResponseBody
    public int restoreShelves(BrowRecored browRecored){
        //1.处理操作一：归还成功之后，状态码修改为3
        BrowRecored browRecored_db = browRecoredService.queryBrowRecoredById(browRecored.getBrowRecoredId());
        browRecored_db.setBookState(3);
        int m = browRecoredService.updateByPrimaryKeySelective(browRecored_db);
        //2.处理操作二：归还之后，该类库层+1
        Integer bookId = browRecored_db.getBookId();
        Book book_db=bookService.selectByPrimaryKey(bookId);
        book_db.setStockNumber(book_db.getStockNumber()+1);
        int n=bookService.updateByPrimaryKeySelective(book_db);
        return 0;
    }


    @RequestMapping(value = "informReturn.do",produces = "application/json;charset=utf-8")
    @ResponseBody
    public int informReturn(BrowRecored browRecored){
        //邮件通知
        emailSend.sendMessage(browRecored.getUserId(),browRecored.getBookId());
        return 0;
    }
    /**
     * 管理员上架图书
     */
    @RequestMapping("uoBook.do")
    @ResponseBody
    public String upBook(Book book,String variesId){
        //1.将书插入数据库中并返回它的id值
        int upBookId = bookService.insert(book);
        //2.将它插book与varies的中间表中
        int n = bookService.insertUpBook(upBookId,Integer.parseInt(variesId));
        if(n>0){
            return "SUCCESS";
        }else{
            return "FAIL";
        }
    }



}
